//
//  AcquireCustomerVC.m
//  ProjectforHDX
//
//  Created by yinda on 16/8/16.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "AcquireCustomerVC.h"
#import "SearchBar.h"
#import "FailurePartsModel.h"

@interface AcquireCustomerVC ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong)SearchBar *searchBar;

@property(nonatomic, strong)NSString *searchKey;

@property(nonatomic ,strong)NSMutableArray *faultedPlates;

@property(nonatomic, strong)NSMutableDictionary *params;
@end

@implementation AcquireCustomerVC

-(NSMutableArray *)faultedPlates
{
    if (!_faultedPlates) {
        _faultedPlates = [NSMutableArray array];
    }
    return _faultedPlates;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestData];
    [self setupView];
}


-(void)requestData
{
    [[BDHUD sharedManager] showBDHUD:self.view title:@"HUD.title"];
    sleep(0.5);
    [[BDHUD sharedManager] dismissHUD];
    
    _params = [NSMutableDictionary dictionary];
    // orderType
    [_params setValue:self.searchKey forKey:@"searchKey"];
    [_params setValue:self.orderType forKey:@"orderType"];

    NSLog(@"%@",_params);
    
    [[BDHUD sharedManager] showBDHUD:self.view title:nil];
    [AFHttpTool postJsonDatawithUrl:@"getMyCustomer" parameters:_params success:^(id responseObject) {
        [[BDHUD sharedManager] dismissHUD];
        if(1==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
                NSArray *data=[responseObject objectForKey:@"data"] ;
            NSLog(@"%@",data);
            
            
            [self.faultedPlates addObjectsFromArray:data];
            [self.tableView reloadData];

        }
        else{
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
            else{
                [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
            }
            
        }
    } fail:^(id responseObject, NSError *error) {
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
    }];
}

//初始化view
-(void)setupView
{
    UITableView *table =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
    table.delegate = self;
    table.dataSource = self;
    [table setFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    self.tableView.backgroundColor = [UtilCheck hexStringToColor:@"F7F5FA" alpha:1.0];
    [self.view addSubview:table];
    self.tableView = table;
    
    UISearchBar *search = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    search.backgroundColor =[UIColor whiteColor];
    [search setImage:BDFILEIMAGENAEM(@"default/iconfont-sousuo") forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    search.placeholder = [UtilCheck language:@"customer.search"];
    UITextField *searchField = [search valueForKey:@"_searchField"];
    
    // Change the search bar placeholder text color
    [searchField setValue:[UtilCheck hexStringToColor:@"ababab" alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];
    searchField.font = CustomFont(13);
    
    self.tableView.tableHeaderView = search;
    
    search.backgroundImage = [self imageWithColor:[UtilCheck hexStringToColor:@"#E8E8E8" alpha:1.0] size:search.bounds.size];
    
    search.delegate = self;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//取消searchbar背景色
- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

#pragma -mark tableview 的 delegate  datasource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.faultedPlates.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];;
 
    UILabel *serverNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 7.5, 100, 30)];
    serverNameLabel.font = CustomFont(14);
    [serverNameLabel setTintColor:[UtilCheck hexStringToColor:@"222222" alpha:1.0]];
    serverNameLabel.text = self.faultedPlates[indexPath.row][@"serverName"];
    [cell.contentView addSubview:serverNameLabel];
    
    UILabel *cityLabel = [[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 150) / 2, 7.5, 120, 30)];
    cityLabel.font = CustomFont(14);
    [cityLabel setTextAlignment:NSTextAlignmentCenter];

    [cityLabel setTintColor:[UtilCheck hexStringToColor:@"222222" alpha:1.0]];
    cityLabel.text = self.faultedPlates[indexPath.row][@"city"];
    [cell.contentView addSubview:cityLabel];
    
    UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 110, 7.5, 100, 30)];
    nameLabel.font = CustomFont(14);
    nameLabel.textAlignment = NSTextAlignmentRight;

    [nameLabel setTintColor:[UtilCheck hexStringToColor:@"222222" alpha:1.0]];
    nameLabel.text = self.faultedPlates[indexPath.row][@"name"];
    [cell.contentView addSubview:nameLabel];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSMutableDictionary *dataDic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:self.faultedPlates[indexPath.row][@"id"],@"faultid",self.faultedPlates[indexPath.row][@"name"],@"name",self.tag,@"tag",self.faultedPlates[indexPath.row][@"is_service_time"],@"is_service_time" ,self.faultedPlates[indexPath.row][@"serverName"],@"serverName",self.faultedPlates[indexPath.row][@"isSite"],@"isSite",nil];
    
    NSLog(@"数据%@",dataDic);
   
    //创建一个消息对象
    NSNotification * notice = [NSNotification notificationWithName:@"customer" object:nil userInfo:dataDic];
    //发送消息
    [[NSNotificationCenter defaultCenter]postNotification:notice];
    [[self navigationController] popViewControllerAnimated:YES];
    
}
#pragma -mark searchbar  的 delegate
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    
    NSMutableArray *ma = [[NSMutableArray alloc]init];
    for (NSDictionary *model in self.faultedPlates) {
        if ([model[@"name"] hasPrefix:[NSString stringWithFormat:@"%@",self.searchKey]]) {
            [ma addObject:model];
        }
    }
    self.faultedPlates = ma;
    [self.tableView reloadData];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"%@",searchBar);
    self.searchKey = searchBar.text;

//    if ([searchText isEqualToString:@""]) {
//        [self.faultedPlates removeAllObjects];
//        [self requestData];
//
//    }else {
        [self.faultedPlates removeAllObjects];
        [self requestData];
//    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45.f;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

@end
